<?php

class stTwitterToolboxController extends stcontroller_2_1 {

    public function __construct($config) {
        parent::__construct($config);
    }

    public function loadAdminCss() { // load more css custom here
        echo "<link rel='stylesheet' href='". $this->config['backendCss']. "prettyphoto/prettyPhoto.css' type='text/css' media='all' />";
      //  echo "<link rel='stylesheet' href='". $this->config['backendCss']. "jquery.tooltip.css' type='text/css' media='all' />";
    }

    public function setConfig($config) {
        $this->config = $config;
        if ($this->actionName == "index") {
            $this->actionName = $config ['default_action'];
        }
        $this->config ['classDir'] = $this->config ['pluginDir']. 'libs/2.1/classes/';
        $this->config ['backendCss'] = $this->config ['pluginPath'] . 'css/backend/';
        $this->config ['backendScript'] = $this->config ['pluginPath'] . 'scripts/backend/';
        $this->config ['frontendCss'] = $this->config ['pluginPath'] . 'css/frontend/';
        $this->config ['frontendScript'] = $this->config ['pluginPath'] . 'scripts/frontend/';
        $this->config ['imagesUrl'] = $this->config ['pluginPath'] . 'images/';
    }
    
    public function loadAdminGlobalScript(){   
     
    }
	protected function registerTabMenu() {
	        if (isset($this->config['admin_tabs'])) {
	            $user = get_current_user_id();
	//            $user = get_user_by('id', $user);
	//            if ($user->user_login != $this->config['userAdminName']) {
	//                $this->config['disable_tabs'][] = 'userList';
	//                $this->config['disable_tabs'][] = 'addOn';
	//            }
	            if(!user_can($user, 'read_private_pages')){
	                $this->config['disable_tabs'][] = 'setting';
	                $this->config['disable_tabs'][] = 'addOn';
	            }
	            $this->setTabMenu($this->config['admin_tabs']);
	        }
    }
    
    public function loadAdminScript() { // load more js custom here
        wp_enqueue_script('common');
        wp_enqueue_script('jquery-color');
        wp_admin_css('thickbox');
        wp_print_scripts('post');
        wp_print_scripts('media-upload');
        wp_print_scripts('jquery');
        wp_print_scripts('jquery-ui-core');
        wp_print_scripts('jquery-ui-tabs');
        wp_print_scripts('tiny_mce');
        wp_print_scripts('editor');
        wp_print_scripts('editor-functions');
        add_thickbox();
        wp_tiny_mce();
        wp_admin_css();
        wp_enqueue_script('utils');
        echo '<script src="http://connect.facebook.net/en_US/all.js"></script>';
       // echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery-ui-timepicker-addon.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';
       // echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'lib/jquery.bgiframe.js"></script>';
       // echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'lib/jquery.dimensions.js"></script>';
       // echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.tooltip.js"></script>';
    }

    public function customAdminEnqueueScript() {
        parent::customAdminEnqueueScript();
    }

    public function loadCss() {
        //this is function import javascript
        parent::loadCss();
    }

    public function loadScript() {
        //this is function import javascript
        parent::loadScript();
    }

    public function activationPlugin() {
        // put your activation code here
        global $wpdb;
        $wpdb->query("CREATE TABLE `st_twitter_list` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`user_id` INT NOT NULL,`id_str` BIGINT NOT NULL,`in_reply_to_status_id_str` BIGINT NOT NULL ,`username` TEXT NOT NULL ,`date` TEXT NOT NULL ,`text` TEXT NOT NULL)");
    }
    public function deactivationPlugin() {
        // put your deactivation code here
        global $wpdb;
    }

    public function registerView() {
        $views = array(
            'menu_child1' => 'default_theme',
            //you can call this action by use these urls:
            // 1.   home_url/menu_child1
            // 2.   home_url/?page=plugin_name&action=menu_child1
            // 3.   home_url/?page=plugin_name&action=menu_child1&ajax=1
            'menu_child2' => 'default_theme'
        );
        $this->setView($views);
    }

   public function dashboard(){
        global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Dashboard';
        
        
	}
   public function twitter_list(){
       global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Tweets';
        $this->view->iconNew = 'Update Tweets';
        $this->view->iconAction = "update();";
        $this->view->plugin_url = trailingslashit( WP_PLUGIN_URL.'/'.dirname( plugin_basename(__FILE__) ));
        $stFacebookToolbox_model = $this->loadmodel("stTwitterList");
        $args = array();
        $args['where'] = ' user_id = '.$current_user->ID. ' AND in_reply_to_status_id_str = ""';
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 'id_str';
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 'desc';
        $args['order'] = array($sort, $sort_type);
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_twitter_list WHERE  user_id = ".$current_user->ID.' AND in_reply_to_status_id_str = ""');
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id_str' => __('Tweet ID', $this->config['plugin_name']),
            'text' => __('Tweet Content', $this->config['plugin_name']),
            'username' => __('Username', $this->config['plugin_name']),
            'date' => __('Time Created', $this->config['plugin_name']),
          
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
   }
   public function sub_twitter_list(){
       global $wpdb,$current_user;
        $this->view->plugin_url = trailingslashit( WP_PLUGIN_URL.'/'.dirname( plugin_basename(__FILE__) ));
        $stFacebookToolbox_model = $this->loadmodel("stTwitterList");
        $args = array();
        $args['where'] = ' user_id = '.$current_user->ID. ' AND in_reply_to_status_id_str = "'.$_POST['id'].'"';
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        else
        {
            $args['order'] = array('id', 'DESC');
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_twitter_list WHERE  user_id = ".$current_user->ID." AND in_reply_to_status_id_str = {$_POST['id']}");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id_str' => __('Tweet ID', $this->config['plugin_name']),
            'text' => __('Tweet Content', $this->config['plugin_name']),
            'username' => __('Username', $this->config['plugin_name']),
            'date' => __('Time Created', $this->config['plugin_name']),

        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
   }
   public function setting(){
    	global $wpdb,$current_user;
   	$this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Settings';
        if(isset($_POST['exit'])){
            $this->updateOption(array('username'=>'','user_token'=>'','user_secrect'=>''));
            echo "<script>window.location ='".get_bloginfo('url')."/wp-admin/admin.php?page=stTwitterToolbox&action=setting';</script>";
        }
        if(isset($_GET['user_token'])){
            $this->updateOption($_GET);
            echo "<script>window.location ='".get_bloginfo('url')."/wp-admin/admin.php?page=stTwitterToolbox&action=setting';</script>";
        }
        $this->view->option = $option = $this->option;
    }
   public function update_twitter(){
       global $wpdb,$current_user;
       $option = $this->option;
       $array = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$option['username']));
       foreach($array as $row){
           $data['text'] = $row->text;
           $data['id_str'] = $row->id_str;
           $data['date'] = $row->created_at;
           $data['user_id'] = $current_user->ID;
           $data['username'] = $row->user->screen_name;
           $data['in_reply_to_status_id_str'] = $row->in_reply_to_status_id_str;
           if($wpdb->get_var("SELECT COUNT(*) FROM st_twitter_list WHERE user_id = ".$current_user->ID." AND id_str = ".$row->id_str) > 0){
               $wpdb->update('st_twitter_list',$data,array('id_str'=>$row->id_str));
           }
           else
           {
               $wpdb->insert('st_twitter_list',$data);
           }
       $id_str[] = $row->id_str;
       
   }
   foreach($wpdb->get_results("SELECT * FROM st_twitter_list WHERE user_id = ".$current_user->ID) as $row){
       if(!in_array($row->id_str, $id_str)){
           $wpdb->query("DELETE FROM st_twitter_list WHERE id_str = ".$row->id_str." AND user_id = ".$current_user->ID);
       }
   }
   $arg = array(
                    'status'    => 'success',
                    'message'   => __('Update successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            die;
}
    public function publish_popup(){
        global $wpdb,$current_user;
        $this->view->type = $_POST['type'];
        $this->view->pic = $_POST['pic'];
        $this->view->img = $_POST['img'];
        $this->view->title = $_POST['title'];
        if($_POST['type'] == 'youtube' || $_POST['type'] == 'slideshare'){
        	$this->view->url = $_POST['url'];
        }
        if(isset($_POST['data'])){
            $publish = 1;
            $url = $_POST['data']['url'];
             if($_POST['data']['publish'] == 0){
                 $publish = 0;
                 if($_POST['data']['type'] == 'youtube'){
                    $this->post_tweet($_POST['data']['content']."\n"."http://www.youtube.com/watch?v=".$_POST['data']['url']);
                    $url = "http://www.youtube.com/watch?v=".$_POST['data']['url'];
                 }
                 elseif($_POST['data']['type'] == 'flick')
                    $this->post_tweet($_POST['data']['content']."\n".$_POST['data']['img']);
                 else
                     $this->post_tweet($_POST['data']['content']."\n".$_POST['data']['url']);
             }
             else
             {
                 $date_array = explode(' ',$_POST['data']['time']);
            	  $date = explode('-',$date_array[0]);
                    $time = explode(':',$date_array[1]);
                    $current =  mktime ($time[0],$time[1],00 ,intval($date[1]) ,intval($date[0]) ,$date[2] );
                    if($current <= mktime(date_i18n("H"),date_i18n("i"),date_i18n("s"),date_i18n("n"),date_i18n("j"),date_i18n("Y"))){
                        $publish = 0;
                        if($_POST['data']['type'] == 'youtube')
                         $this->post_tweet($_POST['data']['content']."\n"."http://www.youtube.com/watch?v=".$_POST['data']['url']);
                        elseif($_POST['data']['type'] == 'flick')
                         $this->post_tweet($_POST['data']['content']."\n".$_POST['data']['img']);
                        else
                         $this->post_tweet($_POST['data']['content']."\n".$_POST['data']['url']);
                    }
             }
                $data['name'] = $_POST['data']['name'];
                $data['username'] = $current_user->user_login;
                $data['type'] = $_POST['type'];
                $data['content'] = $_POST['data']['content'];
                $data['media'] = $url;
                $data['thumb'] = $_POST['data']['img'];
                $data['image_type'] = 0;
                $data['publish_type'] = 'twitter';
                $data['published'] = $publish;
                $data['time'] = ($_POST['data']['time'] != '')?$_POST['data']['time']:date('d-m-Y H:i');
               	$data['page'] = json_encode($_POST['data']['page']);
                $data['created_date'] = date('d-m-Y');
                $data['last_update'] = date('d-m-Y h:m:s');
                $data['user_id'] = $current_user->ID;
                $wpdb->insert('st_publishing',$data);
                $arg = array(
                    'status'    => 'success',
                    'message'   => __('Publish successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
                die;
        }
    }
    function post_tweet($tweet_text) {
      $option = $this->option;
      require_once($this->config ['pluginDir']. 'libs/tmhOAuth.php');
       $tmhOAuth = new tmhOAuth(array(
        'consumer_key'    => $this->config['twitter_consumer_key'],
        'consumer_secret' => $this->config['twitter_consumer_secret'],
        'user_token' => $option['user_token'],
        'user_secret' => $option['user_secrect'],
      ));

      $code = $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array(
            'status' => $tweet_text
        ));
    }
}

?>